package com.flyco.modules.fenxiao.controller;

import java.util.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.flyco.common.api.vo.Result;
import com.flyco.common.system.query.QueryGenerator;
import com.flyco.common.aspect.annotation.AutoLog;
import com.flyco.common.util.BizUtil;
import com.flyco.common.util.HttpUtil;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.fenxiao.entity.DistAccount;
import com.flyco.modules.fenxiao.entity.WxCpDepartment;
import com.flyco.modules.fenxiao.entity.WxCpUser;
import com.flyco.modules.fenxiao.service.IDistAccountService;
import com.flyco.modules.fenxiao.service.IWxCpDepartmentService;
import com.flyco.modules.fenxiao.service.IWxCpUserService;

import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.flyco.modules.stm.entity.StmSales;
import com.flyco.modules.stm.service.IStmSalesService;
import com.flyco.modules.system.entity.SysPartner;
import com.flyco.modules.system.service.ISysPartnerService;
import lombok.extern.slf4j.Slf4j;
import com.flyco.common.system.base.controller.BaseController;
import com.flyco.poi.excel.ExcelImportUtil;
import com.flyco.poi.excel.def.NormalExcelConstants;
import com.flyco.poi.excel.entity.ExportParams;
import com.flyco.poi.excel.entity.ImportParams;
import com.flyco.poi.excel.view.EntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 督导信息
 * @Author: flyco
 * @Date: 2020-07-14
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "督导信息")
@RestController
@RequestMapping("/f/fenxiao/wxCpUser")
public class WxCpUserController extends BaseController<WxCpUser, IWxCpUserService> {
    @Autowired
    private IWxCpUserService wxCpUserService;
    @Autowired
    private IWxCpDepartmentService wxCpDepartmentService;
    @Autowired
    private ISysPartnerService sysPartnerService;
    @Autowired
    private IDistAccountService distAccountService;
    @Autowired
    private IStmSalesService stmSalesService;

    /**
     * 分页列表查询
     *
     * @param wxCpUser
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "督导信息-分页列表查询")
    @ApiOperation(value = "督导信息-分页列表查询", notes = "督导信息-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(WxCpUser wxCpUser,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<WxCpUser> queryWrapper = QueryGenerator.initQueryWrapper(wxCpUser, req.getParameterMap());
        Page<WxCpUser> page = new Page<WxCpUser>(pageNo, pageSize);
        IPage<WxCpUser> pageList = wxCpUserService.page(page, queryWrapper);
        if (pageList.getTotal() > 0) {
            List<SysPartner> partners = sysPartnerService.list();
            Map<Long, String> partnerMaps = partners.stream().collect(Collectors.toMap(SysPartner::getId, SysPartner::getName, (key1, key2) -> key2));
            List<WxCpDepartment> departments = wxCpDepartmentService.list();
            Map<Long, String> departmentMaps = departments.stream().collect(Collectors.toMap(WxCpDepartment::getId, WxCpDepartment::getName, (key1, key2) -> key2));

            for (WxCpUser user : pageList.getRecords()) {
                if (oConvertUtils.isNotEmpty(user.getPartnerId())) {
                    user.setPartnerId_dictText(partnerMaps.get(user.getPartnerId()));
                }
                if (oConvertUtils.isNotEmpty(user.getMainDepartment())) {
                    user.setMainDepartment_dictText(departmentMaps.get(user.getMainDepartment()));
                }
            }
        }
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param wxCpUser
     * @return
     */
    @AutoLog(value = "督导信息-添加")
    @ApiOperation(value = "督导信息-添加", notes = "督导信息-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody WxCpUser wxCpUser) {
        wxCpUserService.save(wxCpUser);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param wxCpUser
     * @return
     */
    @AutoLog(value = "督导信息-编辑")
    @ApiOperation(value = "督导信息-编辑", notes = "督导信息-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody WxCpUser wxCpUser) {
        //role: 1无，2分销员，3导购，4督导，5客户
        wxCpUserService.updateById(wxCpUser);
        WxCpUser dbUser = wxCpUserService.getById(wxCpUser.getId());

        if (oConvertUtils.isNotEmpty(dbUser.getRole())) {
            if (dbUser.getRole().equals(3)) {
                /*LambdaQueryWrapper<StmSales> salesQuery = new LambdaQueryWrapper<>();
                salesQuery.eq(StmSales::getUserId,dbUser.getUserId());
                StmSales sales = stmSalesService.getOne(salesQuery,false);
                if (oConvertUtils.isNotEmpty(sales)) {
                    //sales.setPartnerId(dbUser.getPartnerId());
                    sales.setDelFlag(0);
                } else {
                    sales = new StmSales();
                    sales.setUserId(dbUser.getUserId());
                    sales.setName(dbUser.getName());
                    sales.setAvatar(dbUser.getAvatar());
                    //sales.setPartnerId(dbUser.getPartnerId());
                    //sales.setGender(dbUser.)
                    sales.setPhone(dbUser.getMobile());
                    sales.setDelFlag(0);
                }
                stmSalesService.saveOrUpdate(sales);*/
                stmSalesService.saveOrUpdateFromWxCpUser(dbUser);

            }
        }
        /*
            根据手机号码自动注册用户
         */
        if (oConvertUtils.isNotEmpty(dbUser.getMobile()) && oConvertUtils.isEmpty(dbUser.getMemberId())) {
            Long memberId = getSsoAddMemberId(dbUser.getPartnerId(), dbUser.getMobile(), dbUser.getRole());
            if (! Objects.equals(0L,memberId)) {
                dbUser.setMemberId(memberId);
                WxCpUser updateUser = new WxCpUser();
                updateUser.setMemberId(memberId);
                updateUser.setId(dbUser.getId());
                wxCpUserService.updateById(updateUser);
            }
        }

        if (oConvertUtils.isNotEmpty(dbUser.getMemberId()) && oConvertUtils.isNotEmpty(dbUser.getPartnerId())) {
            /*LambdaQueryWrapper<DistAccount> query = new LambdaQueryWrapper<>();
            query.eq(DistAccount::getMemberId, dbUser.getMemberId());
            query.eq(DistAccount::getPartnerId, dbUser.getPartnerId());*/
            DistAccount dbAccount = distAccountService.getDistAccountByAdmin("" + dbUser.getMemberId() + "-" + dbUser.getPartnerId());
            DistAccount account = new DistAccount();
            if (oConvertUtils.isNotEmpty(dbAccount)) {
                //修改role
                account.setRole(dbUser.getRole());
                //distAccountService.update(account, query);
                account.setId("" + dbUser.getMemberId() + "-" + dbUser.getPartnerId());
                distAccountService.modifyDistAccountByAdmin(account);
            } else {
                //新增记录
                account.setId("" + dbUser.getMemberId() + "-" + dbUser.getPartnerId());
                account.setPartnerId(dbUser.getPartnerId());
                account.setMemberId(dbUser.getMemberId());
                account.setRole(dbUser.getRole());
                account.setState(9);
                account.setLevelId(1L);
                distAccountService.saveDistAccountByAdmin(account);
            }
        }
        return Result.ok("编辑成功!");
    }

    private Long getSsoAddMemberId(Long partnerId, String phone, Integer role){
        try {
            StringBuilder url = new StringBuilder();
            url.append(BizUtil.getSsoUrl());
            url.append("/api/sso/get-add-memberId");
            JSONObject memberRole = new JSONObject();
            memberRole.put("partnerId",partnerId);
            memberRole.put("phone",phone);
            memberRole.put("role",role);
            String result = HttpUtil.postJsonRequest(url.toString(),memberRole.toJSONString());
            log.info("result: {}",result);
            if (oConvertUtils.isNotEmpty(result)) {
                JSONObject resultObj = JSON.parseObject(result);
                if (Objects.equals(resultObj.get("code"), 200)) {
                    return Long.valueOf(resultObj.get("data").toString());
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        return 0L;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "督导信息-通过id删除")
    @ApiOperation(value = "督导信息-通过id删除", notes = "督导信息-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        wxCpUserService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "督导信息-批量删除")
    @ApiOperation(value = "督导信息-批量删除", notes = "督导信息-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.wxCpUserService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "督导信息-通过id查询")
    @ApiOperation(value = "督导信息-通过id查询", notes = "督导信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        WxCpUser wxCpUser = wxCpUserService.getById(id);
        return Result.ok(wxCpUser);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param wxCpUser
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WxCpUser wxCpUser) {
        return super.exportXls(request, wxCpUser, WxCpUser.class, "督导信息");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, WxCpUser.class);
    }

}
